﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TripleGameDAL;

namespace WebApplication2
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                repeaterActiveGames.DataSource = TripleGameDALL.GetAllGames();
                repeaterActiveGames.DataBind();
            }
        }

        protected void buttonStartNewGame_Click(object sender, EventArgs e)
        {
            buttonStartNewGame.Visible = false;
            panelCreateNewGame.Visible = true;
        }

        protected void buttonCreateGame_Click(object sender, EventArgs e)
        {
            Game newGame = new TripleGameDAL.Game();
            User playerOne = new TripleGameDAL.User();
            playerOne.Name = ownerPlayerName.Text;
            TripleGameDALL.CreateUser(playerOne);
            newGame.User1ID = playerOne.ID;
            newGame.User2ID = null;
            string gameState = new String('o', 50);
            newGame.GameState = gameState;
            TripleGameDALL.CreateGame(newGame);
            repeaterActiveGames.DataSource = TripleGameDALL.GetAllGames();
            repeaterActiveGames.DataBind();
            Response.Redirect("~/Game.aspx?id=" + newGame.ID.ToString() + "&player=" + newGame.User1ID.ToString());
        }

        protected string GetUserName(string property)
        {
            int? userID = (int?)Eval(property);
            if (userID == null)
            {
                return "Empty";

            }
            User u = TripleGameDALL.GetUserByID(userID);
            return u.Name;
        }

        protected void timerRefreshGames_Tick(object sender, EventArgs e)
        {
            repeaterActiveGames.DataSource = TripleGameDALL.GetAllGames();
            repeaterActiveGames.DataBind();
            if (this.panelJoinGame.Visible)
            {
                this.scriptManager.SetFocus(this.joinPlayerName);
            }
        }

        protected void joinGame(object sedner, CommandEventArgs e)
        {
            int gameID = int.Parse(e.CommandArgument.ToString());
            var currentGame = TripleGameDALL.GetGameByID(gameID);
            if (this.panelJoinGame.Visible)
            {
                User p2 = new TripleGameDAL.User();
                p2.Name = joinPlayerName.Text;
                TripleGameDALL.CreateUser(p2);
                currentGame.User2ID = p2.ID;
                TripleGameDALL.EditGame(currentGame);
                Response.Redirect("~/Game.aspx?id=" + gameID.ToString() + "&player=" + currentGame.User2ID.ToString());
            }
            else
            {
                this.panelJoinGame.Visible = true;
            }
        }
    }
}
